#include "linux_tcp.h"
// Linux Socket编程接口
#include <sys/socket.h>
// Socket ipv4地址结构接口
#include <netinet/in.h>
// Linux 文件IO接口
#include <unistd.h>
// C库
#include <stdio.h>

#define BACKLOG 1

int LinuxTcpServer(unsigned short port)
{
    char recv_buf[64] = "";
    struct sockaddr_in cient_addr = {0};

    /* 创建socket */
    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_fd < 0) {
        printf("[ERROR] socket fail\n");
        return -1;
    }
    printf("[INFO] socket success\n");

    /* 定义地址结构 */
    struct sockaddr_in server_addr = {
        .sin_port = htons(port),
        .sin_family = AF_INET,
        .sin_addr.s_addr = htonl(INADDR_ANY),
    };

    /* 绑定IP、端口 */
    if (bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        printf("[ERROR] bind fail\n");
        return -1;
    }
    printf("[INFO] bind success\n");


    /* 开始监听 */
    if (listen(sock_fd, BACKLOG) < 0) {
        printf("[ERROR] listen fail\n");
        return -1;
    }
    printf("[INFO] listen success\n");

    /* 等待客户端连接成功 */
    socklen_t clientAddrLen = sizeof(cient_addr);
    int accept_fd = accept(sock_fd, (struct sockaddr *)&cient_addr, &clientAddrLen);
    if (accept_fd < 0) {
        printf("[ERROR] accept fail\n");
        return -1;
    }
    printf("[INFO] accept success\n");

    /* 接收客户端发送的数据 */
    int recv_bytes = recv(accept_fd, recv_buf, sizeof(recv_buf), 0);
    if (recv_bytes < 0) {
        printf("[ERROR] recv fail\n");
        return -1;
    }
    printf("[INFO] recv success %d bytes\n", recv_bytes);
    
    printf("%s\n", recv_buf);

    // 关闭文件
    close(sock_fd);
    close(accept_fd);
    return 0;
}
